package com.lxxin.controller;

import com.lxxin.pojo.Blog;
import com.lxxin.pojo.Result;
import com.lxxin.service.BlogService;
import com.lxxin.utils.RedisUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/detail")
public class DetailController {
    @Autowired
    private BlogService blogService;

    @Autowired
    private RedisUtil redisUtil;

    @GetMapping("/findBlogDetail")
    @ApiOperation("根据博客Id查询博客详情信息")
    public Result findBlogDetail(@RequestParam("id") Long id){
        //存储时间,防止刷阅读数
        Boolean isAdd = true;
        try {
            long time = Long.parseLong(redisUtil.get("addTime") + "");
            //180秒内 浏览量不刷新
            if ((System.currentTimeMillis() / 1000) - time < 180) {
                isAdd = false;
            }
        } catch (Exception e) {
        } finally {
            redisUtil.set("addTime", System.currentTimeMillis() / 1000);
        }
        Blog blogById = blogService.findAndConvertBlogById(id);
        Long wordCount = blogService.findWordCount(id);
        blogById.setWordCount(wordCount);
        Long views = blogService.findViewsById(id, isAdd);
        blogById.setViews(views);
        return Result.builder()
                .statusCode(HttpStatus.OK.value())
                .flag(true)
                .data(blogById)
                .build();
    }

    @PutMapping("/updateBlogComments")
    @ApiOperation("根据博客Id更新评论数")
    public Result updateBlogComments(@RequestParam("id") Long id,
                                     @RequestParam("comments") Long comments) {
        Long saveComment = blogService.updateComments(id, comments);
        String errorMsg = "更新评论数出现异常，更新失败！";
        if (saveComment != 0L) {
            return Result.builder()
                    .flag(true)
                    .statusCode(HttpStatus.OK.value())
                    .build();
        }
        return Result.builder()
                .statusCode(HttpStatus.INTERNAL_SERVER_ERROR.value())
                .errorMsg(errorMsg)
                .build();
    }
}
